<template>

    <div class="container">
      <el-row>
        <el-col :span="15" style="font-size: 22px;margin-top: 6px;">部门管理</el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="11">
          <div style="border:1px solid #ccc;height:100%;">
            <div class="dept_class">
              <p>部门 <el-button type="text" icon="el-icon-plus" size="mini" @click="openAddDept" v-if="perssionButton.indexOf('dept_edit') >-1"></el-button></p>
              <el-tree  :data="deptList"  node-key="value"     default-expand-all  :expand-on-click-node="false"  :highlight-current="true">
           <span class="custom-tree-node" slot-scope="{ node, data }">
            <span @click="findPost(node.data.value)">{{node.label}}</span>
            <span>
               <el-button type="text"  size="mini" @click="updateDept(node.data)" v-if="perssionButton.indexOf('dept_edit') >-1"> 修改 </el-button>
               <el-button type="text"  size="mini" @click="deleteDept(node.data)" v-if="perssionButton.indexOf('dept_delete') >-1"> 删除 </el-button>
              <el-button type="text"  size="mini" @click="openDeptPer(node.data)" v-if="perssionButton.indexOf('dept_power') >-1"> 编辑权限组 </el-button>
            </span>
           </span>
              </el-tree>
             <div style="height:40px;"></div>
            </div>
          </div>
        </el-col>
        <el-col :span="13">
          <div style="border:1px solid #ccc;margin-left:10px;">
            <div class="dept_class">
              <p>职位 <el-button type="text" icon="el-icon-plus" size="mini" @click="openAddPosition" v-if="perssionButton.indexOf('position_edit') >-1"></el-button>
                <span style="color: red;font-size: x-small;float:right;margin-right: 22px;">注：一个部门只有一个一级职位</span></p>
              <el-tree  :data="postList"  node-key="value"   default-expand-all  :expand-on-click-node="false">
           <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>
              {{node.label }}
              <i class="iconfont icon-yijibumenfuzeren" v-if="node.data.postLevel==1"style="margin-left:5px;"></i>
            </span>
            <span>
              <span v-if="perssionButton.indexOf('position_level') >-1">
                 <el-button type="text"  size="mini" v-if="node.data.postLevel==2" @click="setLevel(node.data)">设置一级职位 </el-button>
              </span>
             <span v-if="perssionButton.indexOf('position_level') >-1">
               <el-button type="text"  size="mini" v-if="node.data.postLevel==1"  @click="setLevel(node.data)">取消一级职位 </el-button>
             </span>

              <el-button type="text"  size="mini" @click="openUpdatePosition(node.data)" v-if="perssionButton.indexOf('position_edit') >-1"> 修改 </el-button>
              <el-button type="text"  size="mini" @click="deletePosition(node.data)"v-if="perssionButton.indexOf('position_delete') >-1"> 删除 </el-button>
              <el-button type="text"  size="mini" @click="openPosition(node.data)" v-if="perssionButton.indexOf('dept_power') >-1"> 编辑职位权限 </el-button>
            </span>
          </span>
              </el-tree>
              <div style="height:40px;"></div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!--部门授权-->
      <el-dialog
        title="部门权限" :visible.sync="deptJurisdiction">
        <el-transfer :titles="['未选权限','已选权限']" v-model="checkedGroup" :data="JurisdictionGroup"
                     :props="{key: 'psetId',label: 'psetName'}" style="margin-left: 24px;"></el-transfer>
            <span slot="footer" class="dialog-footer">
              <el-button @click="deptJurisdiction = false">取 消</el-button>
              <el-button type="primary" @click="saveDeptPer">确 定</el-button>
        </span>
      </el-dialog>

      <!--职务授权-->
      <el-dialog
        title="职位权限" :visible.sync="postJurisdiction" width="60%" >
        <el-tabs :tab-position="left" style="height: 100%;">
          <el-tab-pane  v-for="item in positionMeun" :label="`${item.psetName}`" :key="item.psetId">
            <el-transfer :titles="['未选权限','已选权限']"
              :props="{key: 'meId',label: 'meName'}"
              v-model="checkedMeun" :data="item.menusByPsetId" style="margin-left: 24px;"></el-transfer>
          </el-tab-pane>
        </el-tabs>

        <span slot="footer" class="dialog-footer">
            <el-button @click="postJurisdiction = false">取 消</el-button>
            <el-button type="primary" @click="savePostMeun()">确 定</el-button>
       </span>
      </el-dialog>

      <!--新增或修改部门-->
      <el-dialog  title="部门信息" :visible.sync="addDept" width="30%" top="30vh" class="dept_dialog">
        <el-form :model="deptObject"   :rules="rules1"  ref="deptForm"  style="margin-top: 13px;" label-width="100px">
          <el-form-item label="上级部门:" prop="fatherDeptId" v-show="showFatherDept">
            <el-select v-model="deptObject.fatherDeptId" filterable  :disabled="parentsDept">
              <el-option v-for="dept in parentDeptList" :key="dept.deptsId" :label="dept.deptName" :value="dept.deptsId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="deptName" label="部门名称:">
            <el-input  v-model="deptObject.deptName" style="width:217px;"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
           <el-button @click="addDept=false">取 消</el-button>
           <el-button type="primary" @click="saveDept">确 定</el-button>
        </span>
      </el-dialog>
      <!--新增职务-->
      <el-dialog  title="职位名称" :visible.sync="addPosition" width="35%" top="30vh" class="dept_dialog">
        <el-form :model="dynamicValidateForm" ref="dynamicValidateForm"  label-width="80px" class="demo-dynamic">
          <el-form-item
            :label="'职位' + (parseInt(index)+1)"
            v-for="(domain, index) in dynamicValidateForm.domains"
            :key="domain.key"
            :prop="'domains.' + index + '.value'"
            :rules="rules2.postName1"
          >
            <el-input v-model="domain.value" style="width: 238px;"></el-input><el-button @click.prevent="removeDomain(domain)">删除</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="addDomain">新增职位</el-button>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
           <el-button @click="addPosition=false">取 消</el-button>
           <el-button type="primary" @click="addManyPosition">确 定</el-button>
        </span>
      </el-dialog>
      <!--修改职务-->
      <el-dialog  title="职位名称" :visible.sync="updatePost" width="30%" top="30vh" class="dept_dialog">
        <el-form :model="positionObject"   :rules="rules2"  ref="positionForm"  style="margin-top: 13px;">
          <el-form-item prop="postName">
            <el-input  v-model="positionObject.postName"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
           <el-button @click="updatePost=false">取 消</el-button>
           <el-button type="primary" @click="updatePosition">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
  export default {
    data() {
      var checkDeptNmme = (rule, value, callback) => {
        if(this.updateDeptname == value){
          callback();
        }else{
          this.$axios.get("http://localhost:8088/dept/findDeptNameIsNo",
            {params:{deptName:value}}).then(v=>{
            if(v.data == 1){
              callback(new Error('部门名称已存在,请重新输入!'));
            }else{
              callback();
            }
          }).catch();
        }
      };
      var checkPostName = (rule, value, callback) => {
        if(this.updatePostNname == value){
          callback();
        }else{
          this.$axios.get("http://localhost:8088/dept/findPostNameIsNo",
            {params:{deptId:this.deptId,postName:value}}).then(v=>{
            if(v.data == 1){
              callback(new Error('职位名称已存在,请重新输入!'));
            }else{
              callback();
            }
          }).catch();
        }
      };
      var checkPostName2 = (rule, value, callback) => {
        if(this.updatePostNname == value){
          callback();
        }else{
          for(var i=0;i<this.dynamicValidateForm.domains.length;i++){
            for(var y=i+1;y<this.dynamicValidateForm.domains.length;y++){
              if(this.dynamicValidateForm.domains[i].value==this.dynamicValidateForm.domains[y].value){
                callback(new Error('已重复输入职位！'));
                return;
              }
            }
          }
          callback();
        }
      };
      return {
        left:'left',
        radio:true,
        parentsDept:false,//关闭禁用
        parentDeptList:[],//上级部门
        deptJurisdiction:false,//部门权限弹框
        postJurisdiction:false,//职务权限弹框
        deptList:[],//部门集合
        postList:[],//职务集合
        JurisdictionGroup:[],//权限组
        checkedGroup:[],//已选权限组
        deptId:0,//记录选择的部门id
        postId:0,//记录选择的职务id
        positionMeun:[],//子权限
        checkedMeun:[],//已选的子权限
        labelPosition: 'top',
        addDept:false,
        addPosition:false,
        deptObject:{//部门对象
          deptsId:0,
          deptName:'',
          fatherDeptId:'',//上级部门id
        },
        rules1: {//部门名称验证
            deptName:[
              { required: true, message: '部门名称不能为空!', trigger: 'blur' },
               { validator: checkDeptNmme, trigger: 'blur' }
            ],
          fatherDeptId:[
            {required: true, message: '请选择上级部门！', trigger: 'blur'}
            ],
        },
        dynamicValidateForm: {//批量新增职务
          domains: [{
            value: ''
          }]
        },

        positionObject:{
          postId:0,
          postName:'',
          dept:{
            deptsId:0
          },
          postLevel:'',
        },
        rules2: {//职务名称验证
          postName:[
            { required: true, message: '职务名称不能为空', trigger: 'blur' },
            { validator: checkPostName, trigger: 'blur' },
          ],
          postName1:[
            { required: true, message: '职务名称不能为空', trigger: 'blur' },
            { validator: checkPostName, trigger: 'blur' },
              { validator: checkPostName2, trigger: 'blur' }

          ]
        },
        updatePost:false,
        updateDeptname:'',
        updatePostNname:'',
        perssionButton:[],
        showFatherDept:false,
      }
    },
    created :function(){
      this.depts();
      this.deptInfo();
      this.initButton();
    },
    methods: {
        initButton(){
          this.perssionButton=JSON.parse(sessionStorage.getItem("button"));
        },
      //查询出部门
      depts(){
        this.$axios.get("http://localhost:8088/emp/depts").then(v=>{
          this.parentDeptList = v.data;
        }).catch();
      },
      //初始化部门
      deptInfo(){
        this.$axios.get("http://localhost:8088/dept/deptTree").then(v=>{
          this.deptList=v.data;
        }).catch();
      },
      //新增部门按钮
      openAddDept(){
        console.log("aaa:"+this.deptObject.fatherDeptId)
        if (this.$refs.deptForm != undefined) {
          this.$refs.deptForm.resetFields();
        }
        this.deptObject={//部门对象
            deptsId:0,
            deptName:'',
            fatherDeptId:'',//上级部门id
        }
        console.log("aaa:"+this.deptObject.fatherDeptId);
        this.showFatherDept = true,
        this.addDept=true;
        this.parentsDept = false;//关闭选择上级部门的下拉框的禁用
      },
      //修改部门
      updateDept(val){
        this.updateDeptname = val.label;
        if (this.$refs.deptForm != undefined) {
          this.$refs.deptForm.resetFields();
        }
        this.deptObject.deptsId = val.value;
        this.deptObject.deptName = val.label;
        this.deptObject.fatherDeptId = val.fatherDeptId;
        if(this.deptObject.fatherDeptId==0){
          this.showFatherDept = false;
        }else{
          this.showFatherDept = true;
        }
        this.parentsDept = true;//开启选择上级部门的下拉框的禁用
        this.addDept=true;

      },
      //save部门
      saveDept(){
        this.$refs.deptForm.validate((valid) => {
          if (valid) {
            this.$axios.post("http://localhost:8088/dept/saveDept",this.deptObject).then(()=>{
              this.addDept=false;
              this.$refs.deptForm.resetFields();//清空表单
              if(this.deptObject.deptsId>0){
                this.$message.success("修改成功！");
              }else{
                this.$message.success("新增成功！");
              }
              this.deptObject={//部门对象
                deptsId:0,
                deptName:'',
                fatherDeptId:'',//上级部门id
              }
              this.deptInfo();//刷新部门树形图
            }).catch();
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },
      //删除部门
      deleteDept(val){
        //判断需删除的部门下是否存在员工，不存在则可以删除，否则删除失败
        this.$confirm('此操作将永久该部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //删除部门
          this.$axios.post("http://localhost:8088/dept/deleteDept",
            this.qs.stringify({deptId:val.value})).then(v=>{
            console.log("id:"+v.data);
            if(v.data==1){//删除失败
              this.$message.error("存在下属部门 ,删除失败！");
            }else if(v.data==2){
              this.$message.error("存在员工,删除失败！");
            }else{//删除成功
              this.$message.success("删除成功！");
              this.deptInfo();//刷新部门树形图
            }
          }).catch();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //删除动态输入框
      removeDomain(item) {
        var index = this.dynamicValidateForm.domains.indexOf(item)
        if (index !== -1) {
          this.dynamicValidateForm.domains.splice(index, 1)
        }
      },
      //新增输入框
      addDomain() {
        this.dynamicValidateForm.domains.push({
          value: '',
          key: Date.now()
        });
      },
      //打开新增职务弹框
      openAddPosition(){
        if(this.deptId==0){
          this.$message.error("请选择部门！");
        }else {
          if(this.$refs.dynamicValidateForm != undefined){
            this.$refs.dynamicValidateForm.resetFields()//清空
            this.dynamicValidateForm = {//批量新增职务
              domains: [{
                value: ''
              }]
            };
          }
          this.addPosition=true;//打开弹框
        }
      },
      //设置角色级别
      setLevel(val){
        var info = '';
        if(val.postLevel==1){
          info='取消'+val.label+'的一级职位'
        }else if(val.postLevel==2){
          info='设置'+val.label+'为一级职位'
        }

        this.$confirm('此操作将'+info+', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var level = 0;
          if(val.postLevel==1){
            level = 2
          }else if(val.postLevel==2){
            level = 1;
          }
          var positionInfo = JSON.stringify({deptId:this.deptId,postId:val.value,postLevel:level});
          this.$axios.post("http://localhost:8088/dept/set_position_level",
            this.qs.stringify({position:positionInfo})).then(()=>{
            this.$message.success("操作成功！");
            this.findPost(this.deptId);
          }).catch();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作!'
          });
        });

          //取到记录的部门id; deptId


      },
      //新增多个职务
      addManyPosition(){
        this.$refs.dynamicValidateForm.validate((valid) => {
            if (valid) {
              var position = JSON.stringify({deptId:this.deptId,positionList:this.dynamicValidateForm.domains});
              this.$axios.post("http://localhost:8088/dept/add_Position",
                this.qs.stringify({positionList:position})).then(()=>{
                this.$message.success("新增成功！");
                this.$refs.dynamicValidateForm.resetFields()//清空
                this.dynamicValidateForm = {//批量新增职务
                  domains: [{
                    value: ''
                  }]
                };
                this.findPost(this.deptId);
                this.addPosition=false;//关闭弹框
              }).catch();
            } else {
              console.log('error submit!!');
              return false;
            }

        });
      },
      //打开修改职务名称弹框
      openUpdatePosition(val){
        this.updatePostNname = val.label;
        if (this.$refs.positionForm != undefined) {
          this.$refs.positionForm.resetFields();
        }
        this.positionObject.postId = val.value;
        this.positionObject.postName = val.label;
        this.positionObject.dept.deptsId = this.deptId;
        this.positionObject.postLevel=val.postLevel;
        this.updatePost = true;

      },
      //确定修改职务名称
      updatePosition(){
        this.$refs.positionForm.validate((valid) => {
          if (valid) {
            this.$axios.post("http://localhost:8088/dept/update_Position",
              this.positionObject).then(()=>{
              this.$refs.positionForm.resetFields();
              this.findPost(this.deptId);
              this.updatePost = false;
              this.$message.success("修改成功!");

            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },
      //删除职务
      deletePosition(val){
        //判断需删除的职务下是否存在员工，不存在则可以删除，否则删除失败
        this.$confirm('此操作将永久删除该职位, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.post("http://localhost:8088/dept/delete_Position",
            this.qs.stringify({postId:val.value})).then(v=>{

            if(v.data==1){
              this.$message.error("删除失败!");
            }else{
              this.findPost(this.deptId);
              this.$message.success("删除成功！");
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //根据部门查询出对应的职务
      findPost(val){
        this.$axios.get("http://localhost:8088/dept/positionTree",
          {params:{deptId:val}}).then(v=>{
          this.deptId=val;//保存部门id
          this.postList=v.data;
        }).catch()
      },
      //查询所有的权限组
      openDeptPer(val){
        this.$axios.get("http://localhost:8088/dept/permissionGroup",
          {params:{deptId:val.value}}).then(v=>{
          this.JurisdictionGroup=v.data.permissionssetList;//所有权限组
          this.checkedGroup=v.data.deptPermissionssetList;//部门已有的权限组
          this.deptId=val.value;//保存部门id
          this.deptJurisdiction=true;//打开弹框
        }).catch();
      },
      //save部门权限组
      saveDeptPer(){
        var  power=JSON.stringify({deptId:this.deptId,permissionList:this.checkedGroup});
        this.$axios.post("http://localhost:8088/dept/save_permission",
          this.qs.stringify({perminssionsset:power})).then(()=>{
          this.$message.success("授权成功！");
          this.deptJurisdiction=false;//关闭弹框
        }).catch();
      },
      openPosition(val){
        console.log("部门id"+this.deptId);
        this.$axios.get("http://localhost:8088/dept/deptMeun",
          {params:{deptId:this.deptId,postId:val.value}}).then(v=>{
            this.postId = val.value;
            this.positionMeun = v.data.permissionssetList;//子权限
            this.checkedMeun = v.data.positionList;//已选的子权限
            this.postJurisdiction=true;//打开弹框
        }).catch();
      },
      //确定
      savePostMeun(){
        var meun = JSON.stringify({postId:this.postId,positionMeunList:this.checkedMeun});
        this.$axios.post("http://localhost:8088/dept/savePositionMeun",
        this.qs.stringify({positionMeun:meun})).then(()=>{
          this.$message.success("授权成功！");
          this.postJurisdiction=false;//关闭弹框
        }).catch();
      }
    },
    computed: {

    }
  }

</script>

<style>
  .container {
    padding: 20px;
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 5px;
    box-shadow:#ccc 0px 0px 10px;
  }
  .dept_class{
    margin-left: 10px;
    margin-top: 10px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .el-tree-node__content{
    height:34px;
  }
  .el-tree{
    width:98%;
  }
  .el-dialog__body{
    padding: 0px 20px;
  }
  .dept_dialog .el-dialog__footer{
    margin-top: 19px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>

